package com.ipzoe.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP工具类
 * <p>
 * Created 2018/01/19.
 *
 * @author pfzhang
 */
public class IPUtil {

    /**
     * 根据请求获取客户端真实的IP地址
     *
     * @param request 请求
     * @return IP地址
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
